<template>
  <view class="page pageBg-color">
    <com-nav-bar title="分类"></com-nav-bar>

    <scroll-view 
      scroll-y 
      refresher-enabled 
      @refresherrefresh="onRefresh" 
      @scrolltolower="onBottom"
      :refresher-triggered="isTriggered" 
      refresher-background="#fff" 
      class="scroll-view"
    >
      <list-type :dataList="dataList" :isLoading="isLoading" :isHasMore="isHasMore" :isEmpty="isEmpty"></list-type>
    </scroll-view>

  </view>
</template>

<script lang="ts" setup>
import { ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { API } from "@/services/api";

const dataList = ref([]); // 数据列表
const page = ref(1); // 页码
const isLoading = ref(false); // 加载状态
const isHasMore = ref(true); // 是否有更多数据可加载
const isEmpty = ref(true); // 数据是否为空

const isTriggered = ref(false); // 当前下拉刷新状态

// 
onLoad(() => {
  getData();
});

// 
const onRefresh = () => {
  isTriggered.value = true; // 触发下拉刷新动画
  dataList.value = [];
  page.value = 1;
  getData();
};

// 
const onBottom = () => {
  if (isHasMore.value) getData();
};

// 
const getData = () => {
  isLoading.value = true;
  API.classify(page.value, 12)
    .then((res: any) => {
      console.log(`~~~获取 page = ${page.value} 的数据`);
      let newList = [...dataList.value];
      if (page.value === 1) newList = [];
      dataList.value = newList.concat(res.data || []);
      isLoading.value = false;
      isHasMore.value = res.data && res.data.length >= 10;
      isEmpty.value = dataList.value.length <= 0;
      page.value++;
    })
    .catch(() => {
      isLoading.value = false;
      isHasMore.value = false;
      isEmpty.value = true;
    })
    .finally(() => {
      isTriggered.value = false;
    });
};

</script>

<style lang="scss" scoped>
@use "style.scss";
</style>